﻿using System;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Windows.Forms;

namespace Demo
{
    public partial class ObservableTypesForm : Form
    {

		public ObservableTypesForm()
        {
            InitializeComponent();
        }

		private void button1_Click(object sender, EventArgs e)
		{
			listBox1.Items.Clear();
		}

		private void accumulatorBtn_Click(object sender, EventArgs e)
		{
			var o = Observable.Range(1, 5);

			var agg = o.Aggregate(
				0,  //seed
				(accumulatedVal, newIncomingVal) => accumulatedVal + newIncomingVal);

			agg.Subscribe(
				x => listBox1.Items.Add("OnNext " + x.ToString()),
				err => listBox1.Items.Add("OnError " + err.Message ),
				() => listBox1.Items.Add("OnComplete")
				);

		}

		private void distinctValuesBtn_Click(object sender, EventArgs e)
		{
			listBox1.Items.Add("DistinctUntilChanged");
			var subject = new Subject<string>();

			subject.DistinctUntilChanged().Subscribe(
				x => listBox1.Items.Add("OnNext " + x.ToString()),
				err => listBox1.Items.Add("OnError " + err.Message),
				() => listBox1.Items.Add("OnComplete")
			);
			
			subject.OnNext("a");
			subject.OnNext("a");
			subject.OnNext("a");
			subject.OnNext("b");
			subject.OnNext("b");
			subject.OnNext("b");
			subject.OnNext("b");
			subject.OnNext("c");
			subject.OnNext("c");
			subject.OnNext("c");
			subject.OnNext("b");
			subject.OnNext("b");
			subject.OnNext("b");


			listBox1.Items.Add("");
			listBox1.Items.Add("Distinct");
			var subject2 = new Subject<string>();

			subject2.Distinct().Subscribe(
				x => listBox1.Items.Add("OnNext " + x.ToString()),
				err => listBox1.Items.Add("OnError " + err.Message),
				() => listBox1.Items.Add("OnComplete")
			);

			subject2.OnNext("a");
			subject2.OnNext("a");
			subject2.OnNext("a");
			subject2.OnNext("b");
			subject2.OnNext("b");
			subject2.OnNext("b");
			subject2.OnNext("b");
			subject2.OnNext("c");
			subject2.OnNext("c");
			subject2.OnNext("c");
			subject2.OnNext("b");
			subject2.OnNext("b");
			subject2.OnNext("b");
		}


    	private Subject<string> buffer;
		private void asyncSubjectBtn_Click(object sender, EventArgs e)
		{
		    button2.Enabled = true;
			buffer = new Subject<string>();
		    listBox1.Items.Add("start buffering");      //moving average
			buffer.ObserveOn(textBox1).Buffer(5,2).Subscribe(  //can also buffer by Timespan
				lst =>
					{
						foreach (var x in lst)
							listBox1.Items.Add(x);
					});
		}

    	private void button2_Click(object sender, EventArgs e)
		{
			buffer.OnNext(textBox1.Text);
		}

    }

}
